<template>
  <div class="roleList">
    <div class="roleList_buttons">
      <Button type="primary" style="margin-left: 8px" @click="createRoleModel"
        v-if="unlocking('0202010000')">新建角色</Button>
    </div>
    <dt-filter @filter='onFilter' />
    <dt-grid ref="table" :columns="columns1" :list="data1" />
    <page :pageData='pageData' @pageOnChangeFun='pageOnChangeFun'
      @pageOnPageSizeChangeFun='pageOnPageSizeChangeFun'></page>
    <!-- 新建角色 -->
    <Modal v-model="addCreateFlag" width="500" :title="roleTit" :transfer='false'
      @on-cancel="roleCancel">
      <Tabs v-model="TabVal" type="card" @on-click="tabValChange">
        <TabPane label="角色信息" name="name1">
          <div class="roleInfo">
            <p><span><em>*</em>角色名称：</span><span><Input v-model="createData.selRoleName"
                  maxlength="20" placeholder="请输入角色名字" style="width: 200px" /></span></p>
            <p><span><em>*</em>角色类型：</span>
              <span>
                <Select v-model="createData.selRoleType" style="width:200px"
                  @on-change="selChange">
                  <Option :value="1">前台角色</Option>
                  <Option :value="2">后台角色</Option>
                </Select>
              </span>
            </p>
            <p><span><em>*</em>是否参与奖金分摊：</span>
              <span>
                <RadioGroup v-model="createData.bonusAllocation">
                  <Radio :label="1">参与</Radio>
                  <Radio :label="0">不参与</Radio>
                </RadioGroup>
              </span>
            </p>
            <div class="tip">
              <Icon type="ios-quote" /> 提示：选择参与“奖金分摊”，管理员可为该角色设置奖金分摊占比
            </div>
            <p><span>端口权限：</span>
              <span>
                <CheckboxGroup v-model="createData.selPort">
                  <Checkbox label="web">管理端</Checkbox>
                  <Checkbox label="app">app端</Checkbox>
                </CheckboxGroup>
              </span>
            </p>
            <p><span>角色状态：</span>
              <span>
                <RadioGroup v-model="createData.selRoleStatus">
                  <Radio :label="1">启用</Radio>
                  <Radio :label="2">禁用</Radio>
                </RadioGroup>
              </span>
            </p>
            <p><span>备注：</span>
              <span>
                <Input v-model="createData.selRemarks" type="textarea" :rows="4"
                  style="width:300px;height:200px;" :maxlength="300" placeholder="请输入备注..." />
              </span>
            </p>
          </div>
        </TabPane>
        <TabPane label="功能权限" name="name2">
          <div class="treeMenuPc">
            <Tree :data="data2" show-checkbox check-strictly check-directly
              @on-check-change='pcSelChange'></Tree>
          </div>
        </TabPane>
        <TabPane label="数据权限" name="name3" :disabled="tabDisabled">
          <div class="roleInfo">
            <p><span><em>*</em>数据权限类型：</span>
              <span>
                <Select v-model="createData.permissionType" style="width:200px">
                  <Option :value="item.key" v-for="item in $dt.dictInfo().permissionType"
                    :key="item.key">{{item.value}}</Option>
                </Select>
              </span>
            </p>
            <p><span><em>*</em>SOP积分归属组织类型：</span>
              <span>
                <Select v-model="createData.sopOrgType" style="width:200px">
                  <Option :value="1">人员归属案场</Option>
                  <Option :value="2">人员归属组织</Option>
                </Select>
              </span>
            </p>
          </div>
        </TabPane>
      </Tabs>
      <div slot="footer">
        <Button type="text" @click="roleCancel">取消</Button>
        <Button type="primary" @click="getRoleSave">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  import roleMgr from '@/biz/role/role'
  import jurisdictionMgr from '@/biz/jurisdiction/jurisdiction'
  import userMgr from '@/biz/user'
  import columnOpt from './components/roleColumn'
  export default {
    data() {
      return {
        tabDisabled: false,
        // 表格筛选
        filterInfo: {},
        userId: userMgr.info().userId,
        createData: {
          selRoleName: '',
          selRoleType: '',
          selPort: [],
          selRoleStatus: '1',
          selRemarks: '',
          permissionDataList: [],
          permissionType: '',
          bonusAllocation: '',
          sopOrgType: ''
        },
        roleId: '',
        roleTit: '新建角色',
        addCreateFlag: false,
        TabVal: 'name1',

        onresizeHeight: 0,
        pageData: {
          total: 0,
          current: 1,
          rows: 10,
          pageSizeOpts: [10, 20, 30, 40, 50],
        },
        data2: [],
        columns1: [],
        data1: [],
        addEmployee: false,
        addEmployeeMess: {
          roleName: '',
        },

        permissionDataSouce: []

      }
    },
    methods: {
      selChange(val) {
        console.log(val, 'vvvvaaaaaa');
        this.tabDisabled = val == 2 ? true : false
      },
      //表格筛选
      onFilter(data) {
        this.pageData.current = 1
        this.filterInfo = { ...data }
        this.getRoles()
      },

      // 权限树数据
      getPermissionMenuList() {
        return jurisdictionMgr
          .permissionMenuList()
          .then((res) => {
            this.data2 = res
            return this.data2
            console.log(this.data2, 'data2data2data2');
          })
          .catch((err) => {
            this.$Message.error(err)
          })
      },
      pcSelChange(val) {
        console.log(val, '选中的');
        this.createData.permissionDataList = []
        val.forEach((item) => {
          this.createData.permissionDataList.push(item.id)
        })
      },
      tabValChange() {},
      createRoleModel() {
        this.roleTit = '新建角色'
        // this.roleCancel()
        this.addCreateFlag = true
        this.getPermissionMenuList().then(res => {
          this.recursionTree(this.data2, [])
        })

      },

      roleCancel() {
        this.addCreateFlag = false
        this.data2 = []
        this.createData = {
          selRoleName: '',
          selRoleType: '',
          selPort: [],
          selRoleStatus: '1',
          selRemarks: '',
          permissionDataList: [],
          permissionType: '',
          bonusAllocation: '',
        }
        this.TabVal = 'name1'
        // this.getRoles()
        // this.getPermissionMenuList()
      },

      //新建角色
      getRoleSave() {
        if (!this.createData.selRoleName) {
          this.$Message.warning('角色名字不能为空。')
          return false
        }
        if (!this.createData.selRoleType) {
          this.$Message.warning('请选择角色类型。')
          return false
        }
        if (!this.createData.bonusAllocation.toString()) {
          this.$Message.warning('请选择是否参与奖金分摊。')
          return false
        }
        if (!this.tabDisabled && !this.createData.permissionType) {
          this.$Message.warning('请选择数据权限类型。')
          return false
        }
        // this.createData.permissionDataList

        console.log(this.createData.permissionDataList, this.permissionDataSouce, '更改后的，原始的');

        let delPermissionDataList = []
        this.permissionDataSouce.forEach(item => {
          if (this.createData.permissionDataList.findIndex(it => it == item) == -1) {
            delPermissionDataList.push(item)
          }
        })

        let addPermissionDataList = []
        this.createData.permissionDataList.forEach(item => {
          if (this.permissionDataSouce.findIndex(it => it == item) == -1) {
            addPermissionDataList.push(item)
          }
        })
        console.log(delPermissionDataList, addPermissionDataList,
          '删除的，新增的delPermissionDataList');


        let params = {

          roleName: this.createData.selRoleName, //#角色名称
          roleDesc: this.createData.selRemarks, // #备注
          roleType: this.createData.selRoleType, //#角色类型：1-前台角色，2-后台角色
          validate: this.createData.selRoleStatus, //#是否有效(1:有效 2:无效)
          portList: this.createData.selPort, //#端口权限： app、web
          permissionDataList: this.createData.permissionDataList, //#功能权限集合，多个用逗号隔开
          permissionType: this.createData
            .permissionType, //#数据权限类型：1-个人、2-案场、3-部门、4-公司、5-事业部、6-平台
          // phoneLook: 0, // #手机号查看：0-掩号，1-全号
          // phoneExport: 0, //#手机号导出：0-掩号，1-全号
          rewardShareFlag: this.createData.bonusAllocation, //#是否参与奖金分摊：0-不参与，1-参与
          sopOrgType: this.createData.sopOrgType,
          userId: this.userId,
        }
        if (this.roleTit == '新建角色') {
          roleMgr
            .roleSave(params)
            .then((res) => {
              this.$Message.success('角色创建成功。')
              this.roleCancel()
              this.getRoles()
            })
            .catch((err) => {
              this.$Message.error(err)
            })
        } else {
          params.roleId = this.roleId

          params.delPermissionDataList = delPermissionDataList
          params.addPermissionDataList = addPermissionDataList
          roleMgr
            .roleUpdate(params)
            .then((res) => {
              this.$Message.success('角色修改成功。')
              this.roleCancel()
              this.getRoles()
            })
            .catch((err) => {
              this.$Message.error(err)
            })
        }
      },
      //编辑
      editMess(val) {
        this.permissionDataSouce = this.$tool.deepClone(val.permissionDataList)
        console.log(val, '编辑！！！')
        if (val.roleType == 2) {
          this.tabDisabled = true
        } else {
          this.tabDisabled = false
        }
        this.roleTit = '编辑角色'
        this.addCreateFlag = true
        this.createData = {
          selRoleName: val.roleName,
          selRoleType: val.roleType,
          selPort: val.portList,
          selRoleStatus: val.validate,
          selRemarks: val.roleDesc,
          permissionDataList: val.permissionDataList,
          permissionType: val.permissionType.toString(),
          bonusAllocation: val.rewardShareFlag,
          sopOrgType: val.sopOrgType
        }
        this.roleId = val.roleId

        this.getPermissionMenuList().then(res => {
          this.recursionTree(this.data2, val.permissionDataList)
          console.log(val.permissionDataList, this.data2, '44444444');

        })


      },
      recursionTree(arr, ids) {

        arr.forEach((item) => {
          if (ids.includes(Number(item.id))) {
            this.$set(item, 'checked', true)
          } else {
            this.$set(item, 'checked', false)
          }
          if (item.children && item.children.length > 0) {
            this.recursionTree(item.children, ids)
          }
        })
      },
      pageOnChangeFun(page) {
        this.getRoles()
      },
      pageOnPageSizeChangeFun(rows) {
        this.getRoles()
      },
      getRoles() {
        let params = {
          page: this.pageData.current,
          rows: this.pageData.rows,
          ...this.filterInfo
        }
        roleMgr.roleList(params).then((res) => {
          this.data1 = res.list
          this.pageData.total = res.total - 0
        })
      },

      //开启禁用人员
      openAuthority(val) {
        this.$Modal.confirm({
          title: `${val.validate == '1' ? '禁用' : '启用'}角色`,
          content: `<p>请确认,您要${
          val.validate == '1' ? '禁用' : '启用'
        }该角色！</p>`,
          onOk: () => {
            let params = {
              roleId: val.roleId, //#角色id
              validate: val.validate == 1 ? 2 : 1, //#是否有效(1:有效 2:无效)
              userId: this.userId,
            }
            roleMgr
              .roleValidateUpdate(params)
              .then((res) => {
                this.$Message.success('修改成功')
                this.getRoles()
              })
              .catch((err) => this.$Message.error(err))
          },
          onCancel: () => {
            this.$Message.info('您取消了操作。')
          },
        })
      },
      permissionTypeTransformation(value) {
        if (value == 1 || value == 2) {
          let dictionaryData = JSON.parse(this.$tool.getStorage('dictionaryData'))
          let dictLabel = dictionaryData.permissionType.find((item) => {
            return item.key == value
          })
          return dictLabel.value
        }

      },
    },
    mounted() {
      this.columns1 = columnOpt.options(this)
      this.getRoles()

    },
  }
</script>
<style lang="scss" scoped>
  .roleList {
    padding: 20px;
    height: calc(100% - 20px);

    .roleList_buttons {
      display: flex;
      flex-direction: row;
      justify-content: flex-end;

      >span {
        margin-right: auto;
        line-height: 32px;
      }
    }

    .roleInfo {
      p {
        display: flex;
        flex-direction: row;
        margin-top: 15px;
        line-height: 30px;

        >span:first-child {
          width: 185px;
          display: inline-block;
          text-align: right;
          margin-right: 10px;
          line-height: 30px;

          em {
            color: red;
            display: inline-block;
            vertical-align: -3px;
            font-style: normal;
            margin: 5px;
          }
        }
      }
    }

    .treeMenuPc {
      max-height: 400px;
      overflow: auto;
    }

    .tip {
      padding: 2px 10px;
      background: rgba(254, 252, 236, 1);
      display: inline-block;
    }
  }
</style>
<style>
  .N_poptip .ivu-poptip-inner {
    background: rgba(235, 247, 255, 1) !important;
    white-space: normal;
  }

  .featureZ {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 200px;
    display: block;
  }
</style>